<template>
  <div class="pt-6 sm:pt-8">
    <div>
      <!-- Header (match users.vue) -->
      <div class="sm:flex sm:items-center">
        <div class="sm:flex-auto">
          <h1 class="text-base font-semibold text-gray-900 dark:text-gray-100">账户设置</h1>
          <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">管理您的账户信息和密码。</p>
        </div>
      </div>

      <!-- User Info Card -->
      <div class="relative mt-8 -mx-4 sm:-mx-0 bg-white dark:bg-gray-800 shadow rounded-lg mb-6">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 class="text-lg font-medium text-gray-900 dark:text-gray-100">账户信息</h2>
        </div>
        <div class="px-6 py-4">
          <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">用户名</label>
              <p class="mt-1 text-sm text-gray-900 dark:text-gray-100">{{ userInfo?.username }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">角色</label>
              <p class="mt-1 text-sm text-gray-900 dark:text-gray-100">
                <span :class="roleClass(userInfo?.role)">
                  {{ getRoleText(userInfo?.role) }}
                </span>
              </p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">账户状态</label>
              <p class="mt-1 text-sm text-gray-900 dark:text-gray-100">
                <span :class="statusClass(userInfo?.disabled)">
                  {{ userInfo?.disabled ? '已禁用' : '正常' }}
                </span>
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- Change Password Card -->
      <div class="relative mt-8 -mx-4 sm:-mx-0 bg-white dark:bg-gray-800 shadow rounded-lg">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 class="text-lg font-medium text-gray-900 dark:text-gray-100">修改密码</h2>
        </div>
        <div class="px-6 py-4">
          <form @submit.prevent="changePassword" class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300" for="current_password">
                当前密码 <span class="text-red-500">*</span>
              </label>
              <input
                id="current_password"
                v-model="passwordForm.current_password"
                type="password"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-violet-500 focus:border-violet-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                required
                placeholder="请输入当前密码"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300" for="new_password">
                新密码 <span class="text-red-500">*</span>
              </label>
              <input
                id="new_password"
                v-model="passwordForm.new_password"
                type="password"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-violet-500 focus:border-violet-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                required
                placeholder="请输入新密码（至少6位）"
                minlength="6"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300" for="confirm_password">
                确认新密码 <span class="text-red-500">*</span>
              </label>
              <input
                id="confirm_password"
                v-model="passwordForm.confirm_password"
                type="password"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-violet-500 focus:border-violet-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                required
                placeholder="再次输入新密码"
                minlength="6"
              />
            </div>
            
            <div v-if="passwordError" class="text-sm text-red-600 text-center">
              {{ passwordError }}
            </div>
            <div v-if="passwordSuccess" class="text-sm text-green-600 text-center">
              {{ passwordSuccess }}
            </div>
            
            <div class="flex justify-end">
              <button
                type="submit"
                class="px-4 py-2 bg-violet-600 hover:bg-violet-700 text-white font-medium rounded-md transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                :disabled="loading"
              >
                <span v-if="loading">修改中...</span>
                <span v-else>修改密码</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { authApi } from '../api/authService'
import type { UserResponse } from '../api/authService'

const userInfo = ref<UserResponse | null>(null)
const loading = ref(false)
const passwordError = ref('')
const passwordSuccess = ref('')

const passwordForm = reactive({
  current_password: '',
  new_password: '',
  confirm_password: ''
})

const getRoleText = (role?: string) => {
  return role === 'admin' ? '管理员' : '普通用户'
}

const roleClass = (role?: string) => {
  return {
    'text-purple-600 dark:text-purple-400 font-medium': role === 'admin',
    'text-blue-600 dark:text-blue-400': role === 'user'
  }
}

const statusClass = (disabled?: boolean) => {
  return {
    'text-green-600 dark:text-green-400': !disabled,
    'text-red-600 dark:text-red-400': disabled
  }
}

const fetchUserInfo = async () => {
  try {
    const user = await authApi.getCurrentUser()
    userInfo.value = user
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const changePassword = async () => {
  passwordError.value = ''
  passwordSuccess.value = ''
  
  // 验证表单
  if (passwordForm.new_password !== passwordForm.confirm_password) {
    passwordError.value = '新密码与确认密码不匹配'
    return
  }
  
  if (passwordForm.new_password.length < 6) {
    passwordError.value = '新密码长度至少6位'
    return
  }
  
  loading.value = true
  try {
    await authApi.changePassword({
      current_password: passwordForm.current_password,
      new_password: passwordForm.new_password
    })
    
    passwordSuccess.value = '密码修改成功'
    // 清空表单
    passwordForm.current_password = ''
    passwordForm.new_password = ''
    passwordForm.confirm_password = ''
  } catch (error: any) {
    passwordError.value = error?.response?.data?.detail || '密码修改失败'
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>
